package com.example.olingo.server;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.olingo.commons.api.edmx.EdmxReference;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataHttpHandler;
import org.apache.olingo.server.api.ServiceMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class CarsServlet extends HttpServlet {

  private static final long serialVersionUID = 1L;
  private static final Logger LOG = LoggerFactory.getLogger(CarsServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.getOutputStream().println("welcome to nanjing");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
		 HttpSession session = req.getSession(true);
	      DataProvider dataProvider = (DataProvider) session.getAttribute(DataProvider.class.getName());
	      if (dataProvider == null) {
	        dataProvider = new DataProvider();
	        session.setAttribute(DataProvider.class.getName(), dataProvider);
	        LOG.info("Created new data provider.");
	      }

	      OData odata = OData.newInstance();
	      ServiceMetadata edm = odata.createServiceMetadata(new CarsEdmProvider(), new ArrayList<EdmxReference>());
	      ODataHttpHandler handler = odata.createHandler(edm);
	      handler.register(new CarsProcessor(dataProvider));
	      resp.addHeader("name", "jianghui");
	      
	      handler.process(req, resp);
	      
	      LOG.error("CarServlet stared......");
	    } catch (RuntimeException e) {
	      LOG.error("Server Error", e);
	      throw new ServletException(e);
	    }
	}
}
